<template>
  <div>
    <van-search
      v-model="key"
      @input="doSearch"
      placeholder="请输入搜索关键词"
    />

    <div v-if="songList.length == 0" class="search_wrap">
      <p class="hot_title">热门搜索</p>
      <div class="hot_name_wrap">
        <span
          v-for="(item, index) in hotList"
          :key="index"
          @click="doSearch(item.first)"
          class="hot_item"
          >{{ item.first }}</span
        >
      </div>
    </div>

    <div v-else class="search_wrap">
      <p class="hot_title">最佳匹配</p>
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="getSongList"
      >
        <song-item
          v-for="(obj, index) in songList"
          :key="index"
          :title="obj.name"
          :artName="obj.artists[0].name + ' - ' + obj.name"
          :id="obj.id"
        />
      </van-list>
    </div>
  </div>
</template>

<script>
import { searchHotAPI, songSearchAPI } from "@/api";
export default {
  data() {
    return {
      key: "",
      hotList: [],
      songList: [],
      loading: false,
      finished: false,
      page: 1,
      timerId: null,
    };
  },

  methods: {
    async getSongList() {
      let res = await songSearchAPI({
        keywords: this.key,
        limit: 20,
        offset: (this.page - 1) * 20,
      });
      this.songList = [];
      this.page++;
      this.songList.push(...res.data.result.songs);
      this.loading = false;
    },

    async doSearch(key) {
      clearTimeout(this.timerId);
      this.timerId = setTimeout(() => {
        if (key) this.key = key;
        if (this.key == "") return (this.songList = []);
        this.page = 1;
        this.getSongList();
      }, 500);
    },
  },

  async created() {
    let res = await searchHotAPI();
    this.hotList = res.data.result.hots;
  },
};
</script>

<style>
/* 搜索容器的样式 */
.search_wrap {
  padding: 0.266667rem;
}

/*热门搜索文字标题样式 */
.hot_title {
  font-size: 0.32rem;
  color: #666;
}

/* 热搜词_容器 */
.hot_name_wrap {
  margin: 0.266667rem 0;
}

/* 热搜词_样式 */
.hot_item {
  display: inline-block;
  height: 0.853333rem;
  margin-right: 0.213333rem;
  margin-bottom: 0.213333rem;
  padding: 0 0.373333rem;
  font-size: 0.373333rem;
  line-height: 0.853333rem;
  color: #333;
  border-color: #d3d4da;
  border-radius: 0.853333rem;
  border: 1px solid #d3d4da;
}
</style>